package com.styles.codingstyle.services.impl;

import com.styles.codingstyle.dataobject.UserEntity;
import com.styles.codingstyle.exception.CommonException;
import com.styles.codingstyle.mapper.UserMapper;
import com.styles.codingstyle.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @Package com.styles.codingstyle.services.impl
 * @Description:
 * @Author 陈建
 * @Create: 2018-05-30 14:28
 * @Version 1.0
 * @Update: message
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserEntity findById(Long id) {

        /*UserEntity one = userMapper.getOne(id);
        System.out.println(one);*/

        Optional<UserEntity> byId = userMapper.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        } else {
           // throw new CommonException(RESPONSE_ENUM.FAIL_404.getMessage(), RESPONSE_ENUM.FAIL_404.getCode());
           return null;
        }
    }

    @Override
    public UserEntity add(UserEntity userEntity) {
        UserEntity entity = userMapper.saveAndFlush(userEntity);
        return entity;
    }

    @Override
    public void del(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public UserEntity findByUsername(String username) {

        List<UserEntity> list = userMapper.findByUsername(username);
        if (null != list && list.size() == 1) {
            UserEntity userEntity = list.get(0);
            return userEntity;
        }else {
            throw new CommonException("无相关信息",404);
        }
    }
}
